@file:OptIn(ExperimentalMaterialApi::class)

package com.wonderful.eyepetizer.ui.pages.daily

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Share
import androidx.compose.material.pullrefresh.PullRefreshIndicator
import androidx.compose.material.pullrefresh.pullRefresh
import androidx.compose.material.pullrefresh.rememberPullRefreshState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.zIndex
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.paging.compose.collectAsLazyPagingItems
import coil.compose.rememberAsyncImagePainter
import com.wonderful.eyepetizer.R
import com.wonderful.eyepetizer.app.ktx.loadMoreView
import com.wonderful.eyepetizer.data.entity.bean.Item
import com.wonderful.eyepetizer.data.entity.bean.ItemData
import com.wonderful.eyepetizer.ui.pages.detail.VideoDetailActivity
import com.wonderful.eyepetizer.ui.theme.Black_38
import com.wonderful.eyepetizer.ui.theme.Black_54
import com.wonderful.eyepetizer.ui.theme.Black_87
import com.wonderful.eyepetizer.ui.theme.NormalItemColor
import com.wonderful.eyepetizer.ui.theme.White_54
import com.wonderful.eyepetizer.utils.DateUtils
import com.wonderful.eyepetizer.view.Banner
import com.wonderful.eyepetizer.view.TitleBarWidget

/**
 * Desc:
 * @Author: wonderful
 * @Time: 2024/1/19 16:46
 */

const val TEXT_HEADER_TYPE = "textHeader"

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun DailyPage(viewModel: DailyViewModel = viewModel()) {
    val lazyPagingItems = viewModel.pageFlow.collectAsLazyPagingItems()
    val pullRefreshState = rememberPullRefreshState(
        refreshing = viewModel.refreshing.value,
        onRefresh = {
            lazyPagingItems.refresh()
        })
    Column(Modifier.fillMaxSize()) {
        TitleBar()
        Box(
            modifier = Modifier
                .pullRefresh(pullRefreshState)
                .zIndex(-1f)
        ) {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(lazyPagingItems.itemCount) { index ->
                    val pagingItem = lazyPagingItems[index]
                    if (index == 0) {
                        BannerWidget(banners = viewModel.bannerList)
                    } else if (pagingItem?.type == TEXT_HEADER_TYPE) {
                        TitleItemWidget(itemData = pagingItem.data!!)
                    } else {
                        RankItemWidget(itemData = pagingItem?.data!!)
                    }
                }
                loadMoreView(pagingItems = lazyPagingItems)
            }
            PullRefreshIndicator(
                refreshing = viewModel.refreshing.value,
                state = pullRefreshState,
                modifier = Modifier.align(
                    Alignment.TopCenter
                )
            )
        }
    }
}

@Preview(showBackground = true)
@Composable
internal fun TitleBar() {
    TitleBarWidget(title = stringResource(id = R.string.daily_paper), actionsScope = {
        IconButton(onClick = { }) {
            Icon(imageVector = Icons.Default.Search, contentDescription = null, tint = Black_87)
        }
    })
}

@Composable
fun BannerWidget(banners: List<Item>) {
    val context = LocalContext.current
    Banner(data = banners,
        modifier = Modifier
            .padding(15.dp)
            .fillMaxWidth()
            .clip(RoundedCornerShape(4.dp)),
        indicatorModifier = Modifier
            .fillMaxWidth()
            .padding(top = 2.dp),
        onImgPath = {
            banners[it].data!!.cover.feed
        },
        onDesc = {
            Text(
                text = banners[it].data!!.title,
                fontSize = 12.sp,
                color = Color.White,
                modifier = Modifier.padding(top = 5.dp)
            )
        },
        onBannerItemClick = {
            VideoDetailActivity.actionStart(context, banners[it].data!!)
        })
}

@Composable
fun TitleItemWidget(itemData: ItemData) {
    Box(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 5.dp, bottom = 5.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = itemData.text ?: "",
            color = Black_87,
            fontSize = 18.sp,
            fontWeight = FontWeight.Bold
        )
    }
}

@Composable
fun RankItemWidget(itemData: ItemData) {
    val context = LocalContext.current
    Column(modifier = Modifier
        .padding(15.dp, 5.dp, 15.dp, 10.dp)
        .clickable {
            VideoDetailActivity.actionStart(context, itemData)
        }) {
        Box {
            Image(
                painter = rememberAsyncImagePainter(model = itemData.cover.feed),
                contentDescription = null,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(200.dp)
                    .clip(RoundedCornerShape(4.dp)),
                contentScale = ContentScale.Crop
            )
            Box(
                modifier = Modifier
                    .padding(start = 15.dp, top = 10.dp)
                    .background(White_54, shape = CircleShape)
                    .size(44.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(text = itemData.category, color = Color.White)
            }
            Box(
                modifier = Modifier
                    .padding(end = 15.dp, bottom = 10.dp)
                    .background(Black_54, shape = RoundedCornerShape(5.dp))
                    .padding(5.dp)
                    .align(Alignment.BottomEnd),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    text = DateUtils.formatDateMsByMS((itemData.duration * 1000).toLong()),
                    color = Color.White,
                    fontWeight = FontWeight.Bold
                )
            }
        }

        Row(
            modifier = Modifier.padding(top = 10.dp),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Image(
                painter = rememberAsyncImagePainter(model = itemData.author?.icon),
                contentDescription = null,
                modifier = Modifier
                    .size(40.dp)
                    .clip(CircleShape)
            )
            Column(
                modifier = Modifier
                    .weight(1f)
                    .padding(start = 10.dp)
            ) {
                Text(
                    text = itemData.title,
                    color = Color.Black,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
                Text(
                    text = itemData.author?.name ?: "",
                    color = NormalItemColor,
                    modifier = Modifier.padding(top = 2.dp),
                    overflow = TextOverflow.Ellipsis,
                    maxLines = 2
                )
            }
            IconButton(onClick = { /*TODO*/ }) {
                Icon(imageVector = Icons.Default.Share, contentDescription = null, tint = Black_38)
            }
        }

        Divider(thickness = 0.5.dp, modifier = Modifier.padding(top = 5.dp))
    }
}